#version 450

layout(location=0) in vec2 v_Texcoord;

layout(set=0, binding=0, std140) uniform FrameUbo{
    mat4  projMat;
    mat4  viewMat;
    ivec2 resolution;
    uint  frameId;
    float time;
} frameUbo;

layout(set=1, binding=0, std140) uniform MaterialUbo{
    vec4 baseColor0;
    vec4 baseColor1;
    vec4 uvScales;
    float mixValue;
} materialUbo;

layout(set=2, binding=0) uniform sampler2D texture0;
layout(set=2, binding=1) uniform sampler2D texture1;

layout(location=0) out vec4 fragColor;

vec4 getColor(uint index, vec4 inColor, vec2 uvScale) {
    if (inColor.w < 0.0) {
        vec2 retUV = v_Texcoord * uvScale;           // scale
        float uvRotation = inColor.z;
        retUV = vec2(                                // rotation
            retUV.x * sin(uvRotation) + retUV.y * cos(uvRotation),
            retUV.y * sin(uvRotation) + retUV.x * cos(uvRotation)
        );
        retUV += inColor.xy;                        // translation
        return index == 0 ? texture(texture0, retUV) : texture(texture1, retUV);
    } else {
        return inColor;
    }
}

void main(){
    vec4 color0 = materialUbo.baseColor0;
    vec4 color1 = materialUbo.baseColor1;

    if (color0.w < 0.0) color0.y = -frameUbo.time;

    color0 = getColor(0, color0, materialUbo.uvScales.xy);
    color1 = getColor(1, color1, materialUbo.uvScales.zw);
    fragColor = mix(color0, color1, materialUbo.mixValue);
}
